<template>
  <div style="padding: 5px 20px;">
    <br>
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
      <el-form-item label="申请单相关描述">
        <el-input v-model="listQuery.ticket_type" placeholder="请输入申请单类型"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">
          <template #icon>
            <el-icon><Search /></el-icon>
          </template>
          查询
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 表格-->
    <el-table :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column label="申请单类型" prop="ticket_type"></el-table-column>
      <el-table-column label="问题描述" prop="question"></el-table-column>
      <el-table-column label="回答" prop="answer"></el-table-column>
      <el-table-column label="提交人" prop="submitter"></el-table-column>
      <el-table-column label="提交时间">
        <template v-slot="scope">
          <el-icon><Clock /></el-icon>&nbsp;
          <span style="margin-left: 5px">{{ formatDateTime(scope.row.submit_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交次数" prop="submit_count"></el-table-column>
      <el-table-column label="分配管理员" prop="assigned_admin"></el-table-column>
      <el-table-column label="状态" prop="status"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template v-slot="scope">
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="danger" circle @click="deleteVisible(scope.row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="审核" placement="top">
            <el-button type="success" circle @click="auditForm(scope.$index)">
              <el-icon><Check /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
                   :page-sizes="[10]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"
                   :background="true">
    </el-pagination>

    <el-dialog :title="textMap[dialogStatus]" v-model="dialogFormVisible">
      <el-form ref="collectionform" :rules="rules" :model="ruleForm" label-width="120px" label-position="left">
        <el-form-item label="申请单类型" prop="ticket_type">
          <el-input placeholder="申请单类型" v-model="ruleForm.ticket_type"></el-input>
        </el-form-item>
        <el-form-item label="问题描述" prop="question">
          <el-input type="textarea" placeholder="问题描述" v-model="ruleForm.question"></el-input>
        </el-form-item>
        <el-form-item label="回答" prop="answer">
          <el-input type="textarea" placeholder="回答" v-model="ruleForm.answer"></el-input>
        </el-form-item>
        <el-form-item label="提交人" prop="submitter">
          <el-input placeholder="提交人" v-model="this.$store.state.account" readonly></el-input>
        </el-form-item>
        <el-form-item label="提交次数" prop="submit_count">
          <el-input type="number" placeholder="提交次数" v-model="ruleForm.submit_count" readonly></el-input>
        </el-form-item>
        <el-form-item label="分配管理员" prop="assigned_admin">
          <el-input placeholder="分配管理员" v-model="ruleForm.assigned_admin" ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input placeholder="状态" v-model="ruleForm.status" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-if="dialogStatus=='create'" @click="submitCollectionForm('collectionform')">添 加</el-button>
        <el-button type="warning" v-else @click="updateCollectionForm('collectionform')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Search, Edit, Delete,Check,Clock} from '@element-plus/icons-vue';
import axios from 'axios'

export default {
  name: 'DataTickets',
  components: {
    Search,
    Edit,
    Clock,
    Delete,
    Check
  },
  mounted() {
    this.fetchData();
  },
  data() {
    return {
      listLoading: false,
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        ticket_type: '',
        question: '',
        unit_name:'',
      },
      token:'',
      dialogFormVisible: false,
      dialogStatus: 'create',
      textMap: {
        update: '修改申请单',
        create: '添加申请单'
      },
      ruleForm: {
        ticket_id:'',
        ticket_type: '',
        question: '',
        answer: '',
        submitter: '',
        submit_time: '',
        submit_count: 1,
        assigned_admin: '',
        status: '待处理',
      },
      rules: {
        ticket_type: [{ required: true, message: '请输入申请单类型', trigger: 'blur' }],
        question: [{ required: true, message: '请输入问题描述', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入回答', trigger: 'blur' }],
        submitter: [{ required: true, message: '请输入提交人', trigger: 'blur' }],
        submit_count: [{ required: true, message: '请输入提交次数', trigger: 'blur' }],
        assigned_admin: [{ required: true, message: '请输入分配管理员', trigger: 'blur' }],
        status: [{ required: true, message: '请输入状态', trigger: 'blur' }],
      }
    };
  },
  methods: {
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.fetchData();
    },
    fetchData() {

      this.listLoading = true;
      axios.get('http://127.0.0.1:8000/qa/data-tickets1/',{
        params: {
          page: this.listQuery.page,
          limit: this.listQuery.limit,
          ticket_type: this.listQuery.ticket_type,
          question: this.listQuery.question,
          keyword: this.listQuery.unit_name,
          submitter_id: this.$store.state.account,
        },
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + (this.$store.state.token || localStorage.getItem('token'))
        },
        withCredentials: true,
      }).then(response => {
        this.listLoading = false;
        this.list = response.data.results;
        this.total = response.data.count;
        console.log('Received data:', response.data);
      }).catch(error => {
        console.error('Error fetching data:', error);
        this.listLoading = false;
      });
    },
    TJCollectionForm() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    resetForm() {
      this.ruleForm = {
        ticked_id:'',
        ticket_type: '',
        question: '',
        answer: '',
        submitter: this.$store.state.account,
        submit_time: '',
        submit_count: 1,
        assigned_admin: '',
        status: '待处理',
      };
    },
    BJCollectionForm($index) {
      this.ruleForm = JSON.parse(JSON.stringify(this.list[$index]));
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
    },
    submitCollectionForm(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          axios.put('http://127.0.0.1:8000/qa/re_data_ticket/', this.ruleForm).then(response => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$message.success('数据处理成功！');
          }).catch(error => {
            console.error('Error submitting data:', error);
            this.$message.error('数据处理失败！');
          });
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
    auditForm(index) {
      const row = this.list[index];
      this.$confirm(`确定要审核 ${row.ticket_id} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const url = `http://127.0.0.1:8000/qa/re_data_ticket/${row.ticket_id}/`;
        axios.put(url, {
          status: '已处理'
        }, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + (this.$store.state.token || localStorage.getItem('token'))
          },
          withCredentials: true,
        }).then(response => {
          this.fetchData();
          this.$message.success('审核成功');
        }).catch(error => {
          console.error('审核失败！', error);
          this.$message.error('审核失败！请检查网络连接或重试。');
        });
      }).catch(() => {
        // 用户取消审核
        this.$message.info('审核已取消');
      });
    },
    updateCollectionForm(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          axios.put(`http://127.0.0.1:8000/qa/re_data_ticket/${this.ruleForm.ticket_id}/`, this.ruleForm).then(response => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$message.success('数据处理成功！');
          }).catch(error => {
            console.error('Error updating data:', error);
            this.$message.error('数据处理失败！');
          });
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
    deleteVisible(scope) {
      const csrfToken = this.$cookies.get('csrftoken');
      if (!csrfToken) {
        console.error('CSRF token not found');
        this.$message.error('CSRF token not found');
        return;
      }

      this.$confirm(`确定要驳回 ${scope.ticket_id} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const url = `http://127.0.0.1:8000/qa/reject_data_ticket/${scope.ticket_id}/`;
        this.$axios.put(url, { withCredentials: true, headers: { 'X-CSRFToken': csrfToken } })
          .then(response => {
            this.fetchData();
            this.$message.success('驳回成功');
          })
          .catch(error => {
            console.error('Error:', error);
            this.$message.error('驳回数据失败！请检查网络连接或重试。');
            if (error.response && error.response.status === 403) {
              this.$message.error('CORS 策略阻止了请求。请检查后端配置。');
            }
          });
      }).catch(() => {
        // 用户取消删除
      });
    },
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  }
}
</script>
<style>
.answer-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

</style>

